package club.justwill.single.helper;

import club.justwill.single.util.AlipayNotify;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.SystemEnvironmentPropertySource;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by xiangnan on 16-2-2.
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class PayHelper extends BaseHelper {

    public static boolean verifyResult(HttpServletRequest request) {
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化

                if(!Charset.forName("utf-8").newEncoder().canEncode(valueStr)){
                    try {
                         valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                    } catch (UnsupportedEncodingException e) {
                         e.printStackTrace();
                    }
                }

            params.put(name, valueStr);
        }
        return AlipayNotify.verify(params);
    }
}
